

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/favicon.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="xuehaoweng">
  <meta name="keywords" content="">
  
    <meta name="description" content="在微服务架构中，配置管理是一个至关重要的环节。Nacos（Naming and Configuration Service）作为一款优秀的配置中心和服务管理平台，为微服务提供了动态配置服务。本文将介绍如何使用 Nacos 作为 Python 微服务的配置中心，以及如何实现配置的实时监听与自动重启功能。   一、Nacos 集群搭建在微服务架构中，Nacos 作为核心的服务发现和配置管理组件，其稳">
<meta property="og:type" content="article">
<meta property="og:title" content="Python微服务中Nacos的颠覆性应用：构建配置中心与实时监听，竟隐藏着这样的性能优化秘密！">
<meta property="og:url" content="http://blog.xhweng.cn/2025/02/11/nacospythonsdk%E4%BB%8B%E7%BB%8D/index.html">
<meta property="og:site_name" content="有追求的开发者">
<meta property="og:description" content="在微服务架构中，配置管理是一个至关重要的环节。Nacos（Naming and Configuration Service）作为一款优秀的配置中心和服务管理平台，为微服务提供了动态配置服务。本文将介绍如何使用 Nacos 作为 Python 微服务的配置中心，以及如何实现配置的实时监听与自动重启功能。   一、Nacos 集群搭建在微服务架构中，Nacos 作为核心的服务发现和配置管理组件，其稳">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.xhweng.cn/img/file_img/python.jpg">
<meta property="article:published_time" content="2025-02-11T03:07:18.000Z">
<meta property="article:modified_time" content="2025-02-11T03:09:26.215Z">
<meta property="article:author" content="xuehaoweng">
<meta property="article:tag" content="编程语言">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://blog.xhweng.cn/img/file_img/python.jpg">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Python微服务中Nacos的颠覆性应用：构建配置中心与实时监听，竟隐藏着这样的性能优化秘密！ - 有追求的开发者</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"blog.xhweng.cn","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"b3bbb822b3d2a5e2761107c03cf72b8c","google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?b3bbb822b3d2a5e2761107c03cf72b8c";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  



  
<meta name="generator" content="Hexo 7.0.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>有追求的开发者</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Python微服务中Nacos的颠覆性应用：构建配置中心与实时监听，竟隐藏着这样的性能优化秘密！"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2025-02-11 11:07" pubdate>
          2025年2月11日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          2.1k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          18 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Python微服务中Nacos的颠覆性应用：构建配置中心与实时监听，竟隐藏着这样的性能优化秘密！</h1>
            
            
              <div class="markdown-body">
                
                <blockquote>
<p>在微服务架构中，配置管理是一个至关重要的环节。Nacos（Naming and Configuration Service）作为一款优秀的配置中心和服务管理平台，为微服务提供了动态配置服务。本文将介绍如何使用 Nacos 作为 Python 微服务的配置中心，以及如何实现配置的实时监听与自动重启功能。</p>
</blockquote>
<p><img src="https://files.mdnice.com/user/33721/29aef8d3-2412-4222-b33a-9838b0a5ef59.png" srcset="/img/loading.gif" lazyload alt="NACOS"></p>
<h1 id="一、Nacos-集群搭建"><a href="#一、Nacos-集群搭建" class="headerlink" title="一、Nacos 集群搭建"></a>一、Nacos 集群搭建</h1><p>在微服务架构中，Nacos 作为核心的服务发现和配置管理组件，其稳定性和可用性至关重要。</p>
<p><img src="https://files.mdnice.com/user/33721/b76d21e8-8eea-4cd0-8a43-34994d9cdeb5.png" srcset="/img/loading.gif" lazyload alt="NACOS集群"></p>
<h2 id="为什么需要搭建-Nacos-集群"><a href="#为什么需要搭建-Nacos-集群" class="headerlink" title="为什么需要搭建 Nacos 集群?"></a><strong>为什么需要搭建 Nacos 集群?</strong></h2><ol>
<li><p><strong>单点故障风险</strong>：单节点的 Nacos 部署存在单点故障的风险。如果该节点发生故障，所有依赖 Nacos 的微服务将无法进行配置拉取、服务注册与发现，导致整个系统不可用。</p>
</li>
<li><p><strong>性能瓶颈</strong>：在单节点模式下，Nacos 无法有效处理大量请求。在高并发或大数据量的场景中，容易导致响应延迟或系统崩溃。</p>
</li>
<li><p><strong>扩展性差</strong>：单节点无法根据流量需求进行水平扩展，当流量激增时，系统难以应对。</p>
</li>
</ol>
<p>通过集群部署，Nacos 可以实现高可用性和负载均衡，提高系统的稳定性、扩展性和容错能力。</p>
<h2 id="在-NACOS-集群架构中加入-NGINX-是出于什么考虑"><a href="#在-NACOS-集群架构中加入-NGINX-是出于什么考虑" class="headerlink" title="在 NACOS 集群架构中加入 NGINX 是出于什么考虑?"></a><strong>在 NACOS 集群架构中加入 NGINX 是出于什么考虑?</strong></h2><ol>
<li><p><strong>负载均衡</strong>：Nginx 作为反向代理服务器，可以均匀地分发客户端请求到多个 Nacos Server 实例上，从而实现负载均衡，提高系统的处理能力和响应速度。</p>
</li>
<li><p><strong>高可用性</strong>：通过 Nginx 可以实现故障转移和高可用性。如果一个 Nacos Server 节点发生故障，Nginx 可以将流量自动转移到其他可用的 Server 节点上，确保服务的不间断运行。</p>
</li>
<li><p><strong>安全性增强</strong>：Nginx 可以作为第一道防线，对进入 Nacos 集群的所有请求进行过滤和处理，如 SSL&#x2F;TLS 加密、IP 限制等，增加系统的安全性。</p>
</li>
<li><p><strong>性能优化</strong>：Nginx 具有高性能的网络模型和缓存机制，能够有效提升系统整体性能，减少延迟。</p>
</li>
<li><p><strong>简化部署和管理</strong>：通过集中管理 Nginx 配置，可以更方便地对整个 Nacos 集群进行管理和维护。</p>
</li>
<li><p><strong>动态路由</strong>：Nginx 支持根据不同的条件（如 URL、HTTP 头信息）来决定如何转发请求，这为灵活的路由策略提供了可能。</p>
</li>
<li><p><strong>访问控制</strong>：可以通过 Nginx 设置访问控制策略，比如限制某些 IP 地址或域名的访问权限。</p>
</li>
<li><p><strong>日志记录和分析</strong>：Nginx 可以记录详细的访问日志，便于监控和分析网络活动。</p>
</li>
</ol>
<p>加入 Nginx 不仅提升了 Nacos 集群的性能和可靠性，还增强了其安全性和管理的灵活性。</p>
<h2 id="使用-docker-compose-来搭建-NACOS-集群"><a href="#使用-docker-compose-来搭建-NACOS-集群" class="headerlink" title="使用 docker-compose 来搭建 NACOS 集群"></a><strong>使用 docker-compose 来搭建 NACOS 集群</strong></h2><p>使用<strong>Docker Compose</strong>来搭建 Nacos 集群是可行的。Docker Compose 允许通过定义一个 yaml 文件来配置应用程序的服务，从而简化了 Nacos 集群的部署过程。使用 Docker Compose，可以方便地管理多个 Nacos 实例，实现集群的快速部署和扩展。</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br></pre></td><td class="code"><pre><code class="hljs routeros">version: <span class="hljs-string">&quot;3.8&quot;</span><br>services:<br>  nacos1:<br>    hostname: nacos1<br>    container_name: nacos1<br>    image: nacos/nacos-server:latest<br>    volumes:<br>      - ./cluster-logs/nacos1:/home/nacos/logs<br>    ports:<br>      - <span class="hljs-string">&quot;7848:7848&quot;</span><br>      - <span class="hljs-string">&quot;18848:8848&quot;</span><br>      - <span class="hljs-string">&quot;9868:9848&quot;</span><br>      - <span class="hljs-string">&quot;9850:9849&quot;</span><br>    env_file:<br>      <span class="hljs-attribute">PREFER_HOST_MODE</span>=hostname<br>	  <span class="hljs-attribute">NACOS_SERVERS</span>=nacos1:8848 nacos2:8848 nacos3:8848<br>      <span class="hljs-attribute">SPRING_DATASOURCE_PLATFORM</span>=mysql<br>      <span class="hljs-attribute">MYSQL_SERVICE_HOST</span>=nacos-mysql<br>      <span class="hljs-attribute">MYSQL_SERVICE_DB_NAME</span>=nacos_devtest<br>      <span class="hljs-attribute">MYSQL_SERVICE_PORT</span>=3306<br>      <span class="hljs-attribute">MYSQL_SERVICE_USER</span>=nacos<br>      <span class="hljs-attribute">MYSQL_SERVICE_PASSWORD</span>=nacos<br>      <span class="hljs-attribute">MYSQL_SERVICE_DB_PARAM</span>=characterEncoding=utf8&amp;connectTimeout=1000&amp;socketTimeout=3000&amp;autoReconnect=true&amp;useSSL=false&amp;allowPublicKeyRetrieval=true<br>      <span class="hljs-attribute">NACOS_AUTH_IDENTITY_KEY</span>=2222<br>      <span class="hljs-attribute">NACOS_AUTH_IDENTITY_VALUE</span>=2xxx<br>      <span class="hljs-attribute">NACOS_AUTH_TOKEN</span>=SecretKey012345678901234567890123456789012345678901234567890123456789<br>      <span class="hljs-attribute">NACOS_AUTH_ENABLE</span>=<span class="hljs-literal">true</span><br>      <span class="hljs-attribute">NACOS_AUTH_USER_AGENT_AUTH_WHITE_ENABLE</span>=<span class="hljs-literal">true</span><br>    restart: always<br>    depends_on:<br>      nacos-mysql:<br>        condition: service_healthy<br><br>  nacos2:<br>    hostname: nacos2<br>    image: nacos/nacos-server:latest<br>    container_name: nacos2<br>    volumes:<br>      - ./cluster-logs/nacos2:/home/nacos/logs<br>    ports:<br>      - <span class="hljs-string">&quot;7849:7848&quot;</span><br>      - <span class="hljs-string">&quot;18849:8848&quot;</span><br>      - <span class="hljs-string">&quot;9869:9848&quot;</span><br>      - <span class="hljs-string">&quot;9851:9849&quot;</span><br>    env_file:<br>      <span class="hljs-attribute">PREFER_HOST_MODE</span>=hostname<br>	  <span class="hljs-attribute">NACOS_SERVERS</span>=nacos1:8848 nacos2:8848 nacos3:8848<br>      <span class="hljs-attribute">SPRING_DATASOURCE_PLATFORM</span>=mysql<br>      <span class="hljs-attribute">MYSQL_SERVICE_HOST</span>=nacos-mysql<br>      <span class="hljs-attribute">MYSQL_SERVICE_DB_NAME</span>=nacos_devtest<br>      <span class="hljs-attribute">MYSQL_SERVICE_PORT</span>=3306<br>      <span class="hljs-attribute">MYSQL_SERVICE_USER</span>=nacos<br>      <span class="hljs-attribute">MYSQL_SERVICE_PASSWORD</span>=nacos<br>      <span class="hljs-attribute">MYSQL_SERVICE_DB_PARAM</span>=characterEncoding=utf8&amp;connectTimeout=1000&amp;socketTimeout=3000&amp;autoReconnect=true&amp;useSSL=false&amp;allowPublicKeyRetrieval=true<br>      <span class="hljs-attribute">NACOS_AUTH_IDENTITY_KEY</span>=2222<br>      <span class="hljs-attribute">NACOS_AUTH_IDENTITY_VALUE</span>=2xxx<br>      <span class="hljs-attribute">NACOS_AUTH_TOKEN</span>=SecretKey012345678901234567890123456789012345678901234567890123456789<br>      <span class="hljs-attribute">NACOS_AUTH_ENABLE</span>=<span class="hljs-literal">true</span><br>      <span class="hljs-attribute">NACOS_AUTH_USER_AGENT_AUTH_WHITE_ENABLE</span>=<span class="hljs-literal">true</span><br>    restart: always<br>    depends_on:<br>      nacos-mysql:<br>        condition: service_healthy<br>  nacos3:<br>    hostname: nacos3<br>    image: nacos/nacos-server:latest<br>    container_name: nacos3<br>    volumes:<br>      - ./cluster-logs/nacos3:/home/nacos/logs<br>    ports:<br>      - <span class="hljs-string">&quot;7850:7848&quot;</span><br>      - <span class="hljs-string">&quot;18850:8848&quot;</span><br>      - <span class="hljs-string">&quot;9870:9848&quot;</span><br>      - <span class="hljs-string">&quot;9852:9849&quot;</span><br>    env_file:<br>      <span class="hljs-attribute">PREFER_HOST_MODE</span>=hostname<br>	  <span class="hljs-attribute">NACOS_SERVERS</span>=nacos1:8848 nacos2:8848 nacos3:8848<br>      <span class="hljs-attribute">SPRING_DATASOURCE_PLATFORM</span>=mysql<br>      <span class="hljs-attribute">MYSQL_SERVICE_HOST</span>=nacos-mysql<br>      <span class="hljs-attribute">MYSQL_SERVICE_DB_NAME</span>=nacos_devtest<br>      <span class="hljs-attribute">MYSQL_SERVICE_PORT</span>=3306<br>      <span class="hljs-attribute">MYSQL_SERVICE_USER</span>=nacos<br>      <span class="hljs-attribute">MYSQL_SERVICE_PASSWORD</span>=nacos<br>      <span class="hljs-attribute">MYSQL_SERVICE_DB_PARAM</span>=characterEncoding=utf8&amp;connectTimeout=1000&amp;socketTimeout=3000&amp;autoReconnect=true&amp;useSSL=false&amp;allowPublicKeyRetrieval=true<br>      <span class="hljs-attribute">NACOS_AUTH_IDENTITY_KEY</span>=2222<br>      <span class="hljs-attribute">NACOS_AUTH_IDENTITY_VALUE</span>=2xxx<br>      <span class="hljs-attribute">NACOS_AUTH_TOKEN</span>=SecretKey012345678901234567890123456789012345678901234567890123456789<br>      <span class="hljs-attribute">NACOS_AUTH_ENABLE</span>=<span class="hljs-literal">true</span><br>      <span class="hljs-attribute">NACOS_AUTH_USER_AGENT_AUTH_WHITE_ENABLE</span>=<span class="hljs-literal">true</span><br>    restart: always<br>    depends_on:<br>      nacos-mysql:<br>        condition: service_healthy<br>  nacos-mysql:<br>    container_name: nacos-mysql<br>    build:<br>      context: .<br>      dockerfile: ./image/mysql/5.7/Dockerfile<br>    image: example/mysql:5.7<br>    env_file:<br>      <span class="hljs-attribute">MYSQL_ROOT_PASSWORD</span>=root<br>      <span class="hljs-attribute">MYSQL_DATABASE</span>=nacos_devtest<br>      <span class="hljs-attribute">MYSQL_USER</span>=nacos<br>      <span class="hljs-attribute">MYSQL_PASSWORD</span>=nacos<br>      <span class="hljs-attribute">LANG</span>=C.UTF-8<br>    volumes:<br>      - ./nacos-mysql:/var/lib/mysql<br>    ports:<br>      - <span class="hljs-string">&quot;13306:3306&quot;</span><br>    healthcheck:<br>      test: [ <span class="hljs-string">&quot;CMD&quot;</span>, <span class="hljs-string">&quot;mysqladmin&quot;</span> ,<span class="hljs-string">&quot;ping&quot;</span>, <span class="hljs-string">&quot;-h&quot;</span>, <span class="hljs-string">&quot;localhost&quot;</span> ]<br>      interval: 5s<br>      timeout: 10s<br>      retries: 10<br></code></pre></td></tr></table></figure>

<p>使用 compose 模式搭建 Nacos 集群，除了<strong>数据持久化</strong>之外，还需要关注</p>
<ol>
<li><p><strong>集群架构设计</strong>：合理规划集群的节点数量和拓扑结构，确保集群的高可用性和负载均衡</p>
</li>
<li><p><strong>数据库准备</strong>：Nacos 集群需要使用数据库进行数据共享。选择合适的数据库（如 MySQL）并正确配置，确保集群中的 Nacos 实例可以访问和同步数据</p>
</li>
<li><p><strong>配置文件修改</strong>：对于每个 Nacos 节点，需要修改配置文件以指定数据库信息和集群节点信息</p>
</li>
<li><p><strong>网络配置</strong>：确保集群中的所有 Nacos 节点可以相互通信，网络配置是关键</p>
</li>
<li><p><strong>集群管理</strong>：包括集群的启动、监控和维护，确保集群的稳定运行</p>
</li>
</ol>
<p>搭建 Nacos 集群是提高微服务架构性能和可靠性的重要步骤,用 Docker Compose 可以简化集群部署过程，但在部署时还需要注意多个方面，以确保集群的稳定性和效率</p>
<h1 id="二、配置中心搭建"><a href="#二、配置中心搭建" class="headerlink" title="二、配置中心搭建"></a>二、配置中心搭建</h1><p>微服务架构对配置中心的需求极为关键，它要求配置中心能够提供<strong>集中管理、动态更新、配置隔离、版本控制、高可用性、安全性、容错性、可扩展性、实时监控和环境区分</strong>等功能。这些特性确保了微服务配置的一致性、灵活性和系统稳定性，是微服务高效运行的重要保障。</p>
<h2 id="录入配置到-Nacos"><a href="#录入配置到-Nacos" class="headerlink" title="录入配置到 Nacos"></a>录入配置到 Nacos</h2><p>在 Nacos 配置列表中，开发人员需手动录入各个微服务的配置内容。配置以 JSON 格式存储，便于后端程序解析。</p>
<h2 id="微服务拉取配置"><a href="#微服务拉取配置" class="headerlink" title="微服务拉取配置"></a>微服务拉取配置</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">load_config_func</span>(<span class="hljs-params">self, group=<span class="hljs-string">&quot;default&quot;</span>, tenant=<span class="hljs-string">&quot;public&quot;</span></span>):<br>    project_name = self.project_name<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-built_in">all</span>([self.username, self.nacos_password, self.nacos_host, self.nacos_port]):<br>        config_logger.error(<span class="hljs-string">&quot;Nacos credentials are not set in .env file.&quot;</span>)<br>    config_logger.info(<span class="hljs-string">f&quot;正在获取配置: dataId=<span class="hljs-subst">&#123;project_name&#125;</span>; group=<span class="hljs-subst">&#123;group&#125;</span>; tenant=<span class="hljs-subst">&#123;tenant&#125;</span>&quot;</span>)<br>    client = nacos.NacosClient(<br>        server_addresses=<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;self.nacos_host&#125;</span>:<span class="hljs-subst">&#123;self.nacos_port&#125;</span>&quot;</span>,<br>        username=self.username,<br>        password=self.nacos_password<br>    )<br>    nacos_config = client.get_config(project_name, <span class="hljs-string">&#x27;default&#x27;</span>)<br>    config_dict = json.loads(nacos_config)<br>    <span class="hljs-comment"># 将内容写入到CONFIG_FILENAME中</span><br>    <span class="hljs-keyword">try</span>:<br>        <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(CONFIG_FILENAME, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> f:<br>            json.dump(config_dict, f, indent=<span class="hljs-number">4</span>, ensure_ascii=<span class="hljs-literal">False</span>)<br>        config_logger.info(<span class="hljs-string">f&quot;配置中心自动LOAD配置:写入文件成功&quot;</span>)<br>    <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:<br>        config_logger.error(<span class="hljs-string">f&quot;配置中心自动LOAD配置:写入文件失败<span class="hljs-subst">&#123;<span class="hljs-built_in">str</span>(e)&#125;</span>&quot;</span>)<br>    <span class="hljs-keyword">return</span> config_dict<br></code></pre></td></tr></table></figure>

<h2 id="实时监听配置变更"><a href="#实时监听配置变更" class="headerlink" title="实时监听配置变更"></a>实时监听配置变更</h2><ol>
<li>启动配置监听器,该函数创建一个守护线程，用于监听配置变更。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">start_config_watcher</span>(<span class="hljs-params">self</span>):<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> <span class="hljs-built_in">hasattr</span>(self, <span class="hljs-string">&#x27;_watcher_thread&#x27;</span>):<br>        self._watcher_thread = threading.Thread(<br>            target=self._start_config_watcher,<br>            daemon=<span class="hljs-literal">True</span><br>        )<br>        self._watcher_thread.start()<br><span class="hljs-comment"># 监听器</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">_start_config_watcher</span>(<span class="hljs-params">self</span>):<br>    project_name = self.project_name<br>    client = nacos.NacosClient(<br>        server_addresses=<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;self.nacos_host&#125;</span>:<span class="hljs-subst">&#123;self.nacos_port&#125;</span>&quot;</span>,<br>        username=self.username,<br>        password=self.nacos_password<br>    )<br>    client.add_config_watcher(project_name, <span class="hljs-string">&#x27;default&#x27;</span>, self.config_change_callback)<br>    config_logger.info(<span class="hljs-string">&quot;配置监听器已启动&quot;</span>)<br></code></pre></td></tr></table></figure>

<ol start="2">
<li><p>配置变更回调函数,当配置发生变化时，以下回调函数将被触发,该函数将新的变更配置内容写入本地文件，并调用重启后端的函数</p>
</li>
<li><p>自动重启后端</p>
</li>
</ol>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs routeros">def restart_django_runserver(self):<br>    config_logger.<span class="hljs-built_in">info</span>(f<span class="hljs-string">&quot;监听到&#123;self.project_name&#125;的配置发生变化,准备自动重载后端&quot;</span>)<br>    try:<br>        <span class="hljs-keyword">if</span> os.name == <span class="hljs-string">&#x27;nt&#x27;</span>:  # 如果是Windows系统<br>            config_logger.<span class="hljs-built_in">info</span>(<span class="hljs-string">&quot;请手动重启服务&quot;</span>)<br>        <span class="hljs-keyword">else</span>:<br>            subprocess.<span class="hljs-built_in">run</span>(<br>                [<span class="hljs-string">&#x27;supervisorctl&#x27;</span>, <span class="hljs-string">&#x27;-c&#x27;</span>, <span class="hljs-string">&#x27;/app/supervisord_prd.conf&#x27;</span>, <span class="hljs-string">&#x27;restart&#x27;</span>, <span class="hljs-string">&#x27;uwsgi&#x27;</span>],<br>                <span class="hljs-attribute">check</span>=<span class="hljs-literal">True</span><br>            )<br>            config_logger.<span class="hljs-built_in">info</span>(<span class="hljs-string">&quot;后端自动重启成功&quot;</span>)<br>    except subprocess.CalledProcessError as e:<br>        config_logger.<span class="hljs-built_in">error</span>(f<span class="hljs-string">&quot;后端重启失败: &#123;e&#125;&quot;</span>)<br><br></code></pre></td></tr></table></figure>


<p>通过整合python与<strong>nacos-python-sdk</strong>，我们初步构建了一个基于Nacos的微服务配置中心，实现了配置的集中管控、实时监控以及服务的自动重启机制。这一方案显著提升了微服务的稳定性和可维护性，为微服务架构的持续迭代和扩展奠定了坚实的基础。在项目实践中，开发团队可根据具体场景和需求，对配置管理策略进行细化和优化。虽然当前实现的是一个基础版本，但留有广阔的改进空间，未来我们将持续对其进行精雕细琢。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/" class="category-chain-item">编程语言</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/" class="print-no-link">#编程语言</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Python微服务中Nacos的颠覆性应用：构建配置中心与实时监听，竟隐藏着这样的性能优化秘密！</div>
      <div>http://blog.xhweng.cn/2025/02/11/nacospythonsdk介绍/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>xuehaoweng</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2025年2月11日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2025/02/11/git/" title="图解 Git 工作原理：一张图读懂 Git 命令的流转过程">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">图解 Git 工作原理：一张图读懂 Git 命令的流转过程</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2025/02/11/%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9%E5%90%88%E9%80%82%E7%9A%84%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/" title="消息队列选型大战：如何在性能与可靠性之间找到最优解">
                        <span class="hidden-mobile">消息队列选型大战：如何在性能与可靠性之间找到最优解</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      皖ICP备2024038809号-2
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="/img/police_beian.png" srcset="/img/loading.gif" lazyload alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
